<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="16">
        <el-button size="small" type="primary" @click="onShow"
          >添加图片</el-button
        >
        <el-button size="small" type="info" @click="deleteFile"
          >删除图片</el-button
        >
      </el-col>
    </el-row>
    <el-row>
      <span
        v-for="(item, index) in fileList"
        :key="index"
        style="margin-right: 10px"
        v-show="fileList.length > 0"
      >
        <el-image style="width: 200px; height: 200px" :src="item"></el-image>
      </span>
    </el-row>

    <!-- //上传的地址action,必填参数 -->
    <el-dialog title="选择图片" :visible.sync="dialogVisible" width="30%">
      <el-upload
        class="upload-demo"
        drag
        action="http://127.0.0.1:8080/identify/handle"
        multiple
        :on-progress="uploadFile"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件</div>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import { handleUpload, download, recognize } from "../../../api/system/file";
export default {
  name: "Guide",
  data() {
    return {
      info: null,
      file: null,
      fileList: [],
      imageUrl: "",
      dialogVisible: false, //是否显示上传的附件
      fits: ["fill", "contain", "cover", "none", "scale-down"],
      url: "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg",
    };
  },
  mounted() {
    if (localStorage.getItem("imageFile")) {
      const storedFileList = localStorage.getItem("imageFile");
      if (storedFileList) {
        this.fileList = JSON.parse(storedFileList);
      }
    }
  },
  methods: {
    //图片上传时
    uploadFile(event, file, fileList) {
      const fileData = new FormData();
      console.log(file);
      fileData.append("file", file.raw);
      if (file && file.raw && file.raw.type.includes("image")) {
        handleUpload(fileData)
          .then((response) => {
            console.log("上传成功");
            // 检查响应的内容类型
            if (
              response.headers["content-type"] &&
              response.headers["content-type"].startsWith("image/")
            ) {
              // 创建Blob对象
              const blob = new Blob([response.data], {
                type: response.headers["content-type"],
              });
              // 创建URL对象
              this.imageUrl = URL.createObjectURL(blob);
              this.fileList.push(this.imageUrl);
              localStorage.setItem("imageFile", JSON.stringify(this.fileList)); //避免刷新页面后图片丢失
              console.log("imageUrl:", this.imageUrl);
              this.dialogVisible = false;
              // 更新图片显示
              this.updateImagePreview();
            } else {
              console.warn("响应数据不是图片格式");
              this.$confirm("图片上传失败, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              })
                .then(() => {
                  this.dialogVisible = true;
                })
                .catch(() => {
                  this.dialogVisible = false;
                });
            }
          })
          .catch((error) => {
            // console.error("上传失败:", error);
            // 处理错误情况
          });
      } else {
        this.$confirm("请选择图片文件上传, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.dialogVisible = true;
          })
          .catch(() => {
            this.dialogVisible = false;
          });
      }
    },

    //删除列表文件后触发
    handleRemove(file, fileList) {
      console.log("handlePreview", file, fileList);
    },

    //点击文件上传后自动显示的列表
    handlePreview(file) {
      console.log(file);
      recognize();
      download();
    },

    ////删除列表前的提示
    beforeRemove(file, fileList) {
      console.log("beforeRemove", file, fileList);
      return this.$confirm(`确定移除 ${file.name}？`);
    },

    handleExceed(files, fileList) {
      console.log("handleExceed", file, fileList);
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },

    //显示文件上传的附件
    onShow() {
      this.dialogVisible = true;
    },
    //删除
    deleteFile() {
      localStorage.removeItem("imageUrl");
    },
  },
};
</script>
<style scoped>
.el-row {
  margin-bottom: 20px;
}
.el-col {
  border-radius: 4px;
}

.bg-purple {
  background: #d3dce6;
}

.grid-content {
  position: relative;
  border-radius: 4px;
  min-height: 36px;
  margin: 10px;
}

.app-container {
  min-height: calc(100vh - 84px);
  color: #303133;
}
.grid-content-img {
  height: calc(100vh - 184px);
  padding: 20px;
}
.grid-content-right {
  min-height: calc(100vh - 137px);
  padding: 20px;
}

:deep() .upload-demo {
  margin: 20px 0 0 500px;
}
.box-card {
  width: 380px;
}
</style>
